package br.com.universidade.servlets.professor;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.universidade.bean.Professor;
import br.com.universidade.dao.ProfessorDao;
import br.com.universidade.servlets.GenericServlet;
import br.com.universidade.util.enun.ViewEnun;

@WebServlet(urlPatterns="/alterarProfessor")
public class AlterarProfessorServlet extends GenericServlet{

	private static final long serialVersionUID = 1L;
	private static final String PROFESSOR="professor";
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		String codigo = req.getParameter(ViewEnun.Professor.ID.getValue());
		
		ProfessorDao professorDao = new ProfessorDao();
		try {
			Professor professor = professorDao.getById(Integer.parseInt(codigo),Professor.class);
			req.setAttribute(PROFESSOR, professor);
			req.setAttribute(ACTION_FORM,"alterarProfessor");
			req.getRequestDispatcher(JSP_CADASTR_PROFESSOR).forward(req, resp);
		}catch (Exception e) {
			saveErrorMessage(req);
			e.printStackTrace();
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		Professor professor = CadastrarProfessorServlet.preencherEntity(req);
		ProfessorDao professorDao = new ProfessorDao();
		try {
			CadastrarProfessorServlet.validarCampos(req, professor);
			professorDao.update(professor);
			saveSucessMessage(req);
		}catch (NumberFormatException e) {
			saveErrorMessage(req);
		} catch (Exception e) {
			saveErrorMessage(req);
			e.printStackTrace();
		}finally{
			doGet(req, resp);
		}
	}
}
